package v1

import (
	"chat/app"
	"chat/app/common"
	"chat/app/dao"
	"chat/app/model"
	"chat/app/service"
	"chat/utils"
	"context"
	"fmt"
	"github.com/go-playground/validator/v10"
	"strconv"
	"strings"
)

type createGroup struct {
	Name string `from:"name" validate:"required,min=2,max=30"`
	Icon string `from:"icon"`
	Memo string `from:"memo"`
}

// CreateGroupService 创建群组
func CreateGroupService(ctx context.Context, c *app.Context) any {
	// 创建返回信息
	data := make(map[string]interface{})
	code := common.SUCCESS

	name := c.PostForm("name")
	icon := c.PostForm("icon")
	memo := c.PostForm("memo")
	// 验证参数
	valid := validator.New()
	a := createGroup{
		Name: name,
	}
	ok := valid.Struct(a)
	if ok != nil {
		// 翻译成中文
		trans := utils.ValidateTransInit(valid)
		verrs := ok.(validator.ValidationErrors)
		errs := make(map[string]string)
		for key, value := range verrs.Translate(trans) {
			errs[key[strings.Index(key, ".")+1:]] = value
		}
		fmt.Println(errs)
		//fmt.Printf("Err(s):\n%+v\n", ok)
		return common.Response(code, common.GetMsg(code), data)
	}

	// 登录uid
	uid := c.UserInfo["uid"]
	uidInt64 := uid.(int64)

	// 创建群组
	community := model.Community{OwnerId: uidInt64, Name: name, Icon: icon, Memo: memo}
	//dao.CommunityCreate(&community)
	//if community.Id == 0 {
	//	return common.Response(common.ERROR, "群组创建失败", data)
	//}

	// 开启事务 加入群组
	groupBatch := []any{
		&model.Contact{
			OwnerId: uidInt64,
			//ReceiveId: community.Id,
			Cate: model.ConcatCateCommunity,
		},
	}
	if err := dao.CommunityTransactionAuto(&community, groupBatch...); err != nil {
		return common.Response(common.ERROR, "加入群组失败", data)
	}

	return common.Response(code, "群组创建成功", data)
}

type joinGroup struct {
	Name string `from:"name" validate:"required,min=2,max=30"`
	Memo string `from:"memo"`
}

// JoinGroupService 加入群组
func JoinGroupService(ctx context.Context, c *app.Context) any {
	// 创建返回信息
	data := make(map[string]interface{})
	code := common.SUCCESS

	name := c.PostForm("name")
	memo := c.PostForm("memo")
	// 验证参数
	valid := validator.New()
	a := joinGroup{
		Name: name,
	}
	ok := valid.Struct(a)
	if ok != nil {
		// 翻译成中文
		trans := utils.ValidateTransInit(valid)
		verrs := ok.(validator.ValidationErrors)
		errs := make(map[string]string)
		for key, value := range verrs.Translate(trans) {
			errs[key[strings.Index(key, ".")+1:]] = value
		}
		fmt.Println(errs)
		//fmt.Printf("Err(s):\n%+v\n", ok)
		return common.Response(code, common.GetMsg(code), data)
	}

	// 查找群租
	userWhere := "name = ?"
	groupArgs := []any{name}
	community, rowsAffected := dao.CommunityGetOne(userWhere, groupArgs...)
	if !rowsAffected {
		return common.Response(common.ERROR, "您要加入的群不存在", data)
	}
	receiveId := community.Id // 群组id

	// 我自己 uid
	uid := c.UserInfo["uid"]
	uidInt64 := uid.(int64)

	// 检查是否已经在群里
	where := "owner_id = ? and receive_id = ? and cate = ?"
	args := []any{
		uidInt64,
		receiveId,
		model.ConcatCateCommunity,
	}
	_, groupRowsAffected := dao.ContactGetOne(where, args...)
	if groupRowsAffected {
		return common.Response(common.ERROR, "已经加入该群了", data)
	}

	// 入群
	joinContact := []model.Contact{
		{
			OwnerId:   uidInt64,
			ReceiveId: receiveId,
			Cate:      model.ConcatCateCommunity,
			Memo:      memo,
		},
	}
	if err := dao.ContactCreateBatch(&joinContact); err != nil {
		return common.Response(common.ERROR, "加入群组失败", data)
	}

	return common.Response(code, "加入群组成功", data)
}

type groupData struct {
	Id           int64  `json:"id"`
	Name         string `json:"name"`
	OwnerId      int64  `json:"owner_id"`
	Icon         string `json:"icon"`
	Memo         string `json:"memo"`
	CreateAt     int64  `json:"create_at"`
	Nickname     string `json:"nickname"`
	MessageTotal int64  `json:"message_total"`
}

// GroupListService 群组列表
func GroupListService(ctx context.Context, c *app.Context) any {

	// 创建返回信息
	resultData := make(map[string]any)
	code := common.SUCCESS

	// 参数
	var page int
	var err error
	if page, err = strconv.Atoi(c.PostForm("page")); err != nil {
		page = 1
	}
	if page <= 0 {
		page = 1
	}
	var pageSize int
	if pageSize, err = strconv.Atoi(c.PostForm("pageSize")); err != nil {
		pageSize = 100
	}

	// uid
	uid := c.UserInfo["uid"]

	// 查询列表
	where := "contact.owner_id = ? and contact.cate = ?"
	args := []any{uid, model.ConcatCateCommunity}
	offset := (page - 1) * pageSize
	limit := pageSize
	CommunityList, total := dao.CommunityJoinContactList(limit, offset, where, args...)

	var length int
	var resultList []groupData
	if total > 0 {
		length = len(*CommunityList)
		resultList = make([]groupData, length)
		for key, item := range *CommunityList {
			resultList[key].Id = item.Id
			resultList[key].Name = item.Name
			resultList[key].OwnerId = item.OwnerId
			resultList[key].Icon = item.Icon
			resultList[key].Memo = item.Memo
			resultList[key].CreateAt = item.CreateAt
			resultList[key].Nickname = item.Nickname
			resultList[key].MessageTotal = 0
		}
		resultData["list"] = resultList
	} else {
		resultData["list"] = make([]groupData, 0)
	}
	resultData["page"] = service.PagesService(page, pageSize, total)

	return common.Response(code, common.GetMsg(code), resultData)
}
